package com.xin.data.simbapesa.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewbinding.ViewBinding;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.activity.SimbaCustomerServiceActivity;
import com.xin.data.simbapesa.activity.SimbaOrderStateActivity;
import com.xin.data.simbapesa.activity.SimbaOrderStateActivity1;
import com.xin.data.simbapesa.adapter.ApplyAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseFragment;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaRepayFragmentBinding;
import com.xin.data.simbapesa.obj.SimbaDetailItemInfo;
import com.xin.data.simbapesa.obj.SimbaOrderRepayInfo;
import com.xin.data.simbapesa.obj.SimbaPlatformNotice;
import com.xin.data.simbapesa.obj.SimbaRepayInfo;
import com.xin.data.simbapesa.obj.SimbaUserProcess;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.NumUtils;
import com.xin.data.simbapesa.utils.PhoneUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.ViewUtils;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class RePayFragment extends BaseFragment<SimbaRepayFragmentBinding> {


    List<SimbaDetailItemInfo> dataList;

    ApplyAdapter adapter;


    String orderId;


    boolean isOverdue;

    SimbaRepayInfo repay;


    BaseActivity<ViewBinding> mActivity;

    StateFragment2.OnRefreshState2Listener onRefreshStateListener;


    @Override
    public void onAttach(@androidx.annotation.NonNull Context context) {
        super.onAttach(context);
        try {
            onRefreshStateListener = (StateFragment2.OnRefreshState2Listener) context;
        } catch (ClassCastException ignored) {
        }
    }


    @Override
    protected SimbaRepayFragmentBinding initViewBinding(LayoutInflater inflater, ViewGroup container) {
        return SimbaRepayFragmentBinding.inflate(inflater);
    }

    @Override
    protected void initView() {


        mActivity = (BaseActivity<ViewBinding>) getActivity();

        binding.getRoot().setPadding(0, 0, 0, 0);

        mActivity.setStatusBarHeight(binding.refresh);


        orderId = getActivity().getIntent().getStringExtra("orderId");

        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P57, "");
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
        });

        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P58, "");
            PU.userBuriedAllPoint(getActivity());
            getOrderRepayH5();
        });

        binding.refresh.setOnRefreshListener(() -> {
            PU.userBuriedPoint(PU.P60, "");
            repayInfo();
            if (onRefreshStateListener != null) {
                onRefreshStateListener.onLoadState();
            }
        });

        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager1);
        int d1 = ResUtils.d(R.dimen.dp_6);
        binding.recyclerView.addItemDecoration(new SimbaSpaceItemDecoration(d1, d1, getActivity()));
        dataList = new ArrayList<>();
        adapter = new ApplyAdapter(dataList);
        binding.recyclerView.setAdapter(adapter);

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P55;
        UP_TYPE2 = PU.P56;
    }

    @Override
    public void onResume() {
        super.onResume();
        repayInfo();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isOverdue) {
            PU.userBuriedAllPoint(getActivity());
        }
    }

    @SuppressLint("SetTextI18n")
    void loadData() {
        if (getActivity() != null && binding != null) {

            if (repay != null) {

                showNotice();

                dataList.clear();

                binding.tvDate.setText(repay.getRepayDate());

//                SimbaDetailItemInfo itemInfo1 = new SimbaDetailItemInfo();
//                itemInfo1.setShowName(ResUtils.s(R.string.state2_title2));
//                itemInfo1.setShowDetail(repay.getAmount()+repay.getCurrency());
//                itemInfo1.setTitle("YES");
//                dataList.add(itemInfo1);


                String overdueday = repay.getOverdueDay();
                if (TextUtils.isEmpty(overdueday)) {
                    overdueday = "0";
                }
                int d = Integer.parseInt(overdueday);
                if (d > 0) {
                    isOverdue = true;

                    binding.tvAmount.setTextColor(Color.parseColor("#FF5A01"));
                    binding.tvState.setTextColor(Color.parseColor("#FF6262"));
                    binding.tvState.setText(ResUtils.s(R.string.repay_state2));

                } else {

                    binding.tvAmount.setTextColor(Color.parseColor("#FFFFFF"));
                    binding.tvState.setTextColor(Color.parseColor("#317600"));
                    binding.tvState.setText(ResUtils.s(R.string.repay_state1));

                }

                binding.tvAmount.setText(repay.getRepayAmount());


                for (SimbaDetailItemInfo item : repay.getDetailItemList()) {
                    if (!TextUtils.isEmpty(item.getShowName()) && !TextUtils.isEmpty(item.getShowDetail())) {
                        item.setTitle("YES");
                        dataList.add(item);
                    }
                }


                adapter.updateAllData();

            }

        }
    }

    void showNotice() {
        if (mActivity != null && !isHidden() && binding != null) {
            SimbaUserProcess process = SimbaApp.getInstance().getProcess();
            if (process != null) {
                if ((!TextUtils.isEmpty(process.getWhatsappFlag()) && !process.getWhatsappFlag().equals("YES")) && (!TextUtils.isEmpty(process.getSmsFlag()) && !process.getSmsFlag().equals("YES")) && (!TextUtils.isEmpty(process.getTelegramFlag()) && !process.getTelegramFlag().equals("YES"))) {
                    if (SimbaApp.getInstance().getAppInfo() != null) {
                        SimbaPlatformNotice platformNotice = SimbaApp.getInstance().getAppInfo().getPlatformNotice1();
                        if (platformNotice != null && platformNotice.getShowNotice().equals("YES")) {
                            mActivity.showTipsDialog(ResUtils.s(R.string.noticeTitle), "", ResUtils.s(R.string.birth_btn), platformNotice.getNoticeInfo(), true, new BaseDialog.BtnClickListener() {
                                @Override
                                public void btnOnClickOk() {

                                }

                                @Override
                                public void btnOnClickCancel() {

                                }

                                @Override
                                public void btnOnClickColse() {

                                }
                            });
                        }
                    }
                }
            }
        }
    }

    void repayInfo() {
        if (binding != null && mActivity != null) {
            mActivity.showLoading("");
            JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[15]);
            json.addProperty("oldFlag", "YES");

            HashMap<String, String> heads = new HashMap<>();
            heads.put("product", U.URL_PRODUCT);
            if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
                heads.put("country", U.URL_PRODUCT);
            }
            String data = AESCryptUtilJar.encryptDefault(json.toString());
            LogUtil.e("me", json + "--repayInfo post--" + data);
            RxHttp.post(U.commonUrl, data, heads)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {

                            if (binding != null) {
                                if (mActivity != null) {
                                    mActivity.hideLoading();
                                }
                                binding.refresh.setRefreshing(false);
                                if (!TextUtils.isEmpty(s)) {
                                    String json1 = AESCryptUtilJar.decryptDefault(s);
                                    LogUtil.e("me", "repayInfo json->" + json1);
                                    if (JsonParse.getCode(json1)) {
                                        repay = JsonParse.repayInfoJson2Obj(json1);
                                        loadData();
                                    }
                                }
                            }

                        }

                        @Override
                        public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                            if (binding != null) {
                                binding.refresh.setRefreshing(false);
                                if (mActivity != null) {
                                    mActivity.hideLoading();
                                    mActivity.showFailedDialog(new BaseDialog.BtnClickListener() {
                                        @Override
                                        public void btnOnClickOk() {
                                            repayInfo();
                                        }

                                        @Override
                                        public void btnOnClickCancel() {

                                        }

                                        @Override
                                        public void btnOnClickColse() {

                                        }
                                    });
                                }
                            }
                            if (e != null) {
                                LogUtil.e("me", "repayInfo e->" + e);
                            }
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        }
    }

    void getOrderRepayH5() {

        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[16]);
//        json.addProperty("orderId", orderId);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }

        String data = AESCryptUtilJar.encryptDefault(json.toString());

        LogUtil.e("me", json + "<-orderRepayH5 pson->" + data);

        mActivity.showLoading("");
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (binding != null) {
                            if (mActivity != null) {
                                mActivity.hideLoading();
                            }
                            if (!TextUtils.isEmpty(s)) {
                                String json1 = AESCryptUtilJar.decryptDefault(s);
                                LogUtil.e("me", "orderRepayH5 json->" + json1);
                                if (JsonParse.getCode(json1)) {
                                    SimbaOrderRepayInfo orderRepayBean = JsonParse.getOrderRepayH5Json2Obj(json1);
                                    if (orderRepayBean != null) {
                                        toNext(orderRepayBean);
                                    }
                                } else {
                                    if (mActivity != null) {
                                        mActivity.showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (binding != null && mActivity != null) {
                            mActivity.hideLoading();
                            mActivity.showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    void toNext(SimbaOrderRepayInfo orderRepayBean) {

        boolean isAcc = PhoneUtils.isAccM(getActivity());
        if (isAcc) {
            Intent intent = new Intent(getActivity(), SimbaOrderStateActivity1.class);
            intent.putExtra("thirdOrderId", orderRepayBean.getThirdOrderId());
            intent.putExtra("orderId", orderId);
            if (repay != null) {
                intent.putExtra("amount", repay.getRepayAmount());
                intent.putExtra("repayDate", repay.getRepayDate());
            }
            startActivity(intent);
        } else {
            if (!TextUtils.isEmpty(orderRepayBean.getRepayUrl()) || !TextUtils.isEmpty(orderRepayBean.getUrl())) {
                String url = orderRepayBean.getUrl();
                if (TextUtils.isEmpty(url)) {
                    url = orderRepayBean.getRepayUrl();
                }
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.parse(url);
                intent.setData(uri);
                startActivity(intent);
            } else if (!TextUtils.isEmpty(orderRepayBean.getThirdOrderId())) {
                Intent intent = new Intent(getActivity(), SimbaOrderStateActivity.class);
                intent.putExtra("thirdOrderId", orderRepayBean.getThirdOrderId());
                intent.putExtra("orderId", orderId);
                if (repay != null) {
                    intent.putExtra("amount", repay.getRepayAmount());
                    intent.putExtra("repayDate", repay.getRepayDate());
                }
                startActivity(intent);
            }
        }

    }


}
